<template>
  <div :id="baiduMapId">
    <baidu-map
      class="bm-view"
      ak="pr9OvF8jfWcvEpojMlYuOWKCzccuaesn"
      :style="{ height: baiduMapWidth }"
      :center="centerOwn"
      :map-click= "false"
      :zoom="zoom"
      :scroll-wheel-zoom="true"

      @ready="handler"
    >
      <slot>
      <bm-navigation
        v-if="hasBmNavigation"
        anchor="BMAP_ANCHOR_BOTTOM_RIGHT"
        :offset="{width: 35, height: 150}"
        :showZoomInfo="false"
        type="BMAP_NAVIGATION_CONTROL_ZOOM"
      ></bm-navigation>
      <bm-overview-map v-if="hasBmOverviewMap" anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :isOpen="true"></bm-overview-map>
      <!-- <bm-marker :position="markerPoint" :dragging="true" animation="BMAP_ANIMATION_BOUNCE" :icon="{url: 'http://developer.baidu.com/map/jsdemo/img/fox.gif', size: {width: 300, height: 157}}"></bm-marker> -->
      <bm-point-collection
        v-if="hasBmPointCollection"
        :points="points"
        shape="BMAP_POINT_SHAPE_STAR"
        color="red"
        size="BMAP_POINT_SIZE_SMALL"
        @click="clickHandler"
      ></bm-point-collection>
      <!-- <my-overlay
          :position="{lng: 116.404, lat: 39.915}"
          text="点击我"
          :active="active"
          @mouseover.native="active = true"
          @mouseleave.native="active = false">
      </my-overlay>-->
      <!-- <bm-overlay
    pane="labelPane"
    :class="{sample: true, active}"
    @draw="draw"
    @mouseover.native="active = true"
    @mouseleave.native="active = false">
    <div @click="handleClick">我爱北京天安门</div>
      </bm-overlay>-->

      <MyMarker v-if="hasMyMarker" v-for="(markerPointItem,index) in markerPointsList" :markerPoint="markerPointItem.point" :markerIcon="markerPointItem.iconUrl" :key="index"/>

      <MyMarkerClusterer v-if="hasMyMarkerClusterer" :markerPoints="markerPointsNew" @handleChangeMyVideoShow="handleChangeMyVideoShow" />

      <myPolyline :bmap="_map" :BMap="_BMap" :icons="icons" v-if="hasMyPollyline&&renderMap" strokeColor="#3591ff" :strokeOpacity="1" :strokeWeight="6" :polylinePath="polylinePath1" @handleChangePolylinePath="handleChangePolylinePath1"/>
      <!-- <myPolyline v-if="hasMyPollyline" strokeStyle="dashed" :strokeOpacity="0" strokeColor="#fff" :strokeWeight="2" :polylinePath="polylinePath2" @handleChangePolylinePath="handleChangePolylinePath2" />
	-->
      <MyCircle v-if="hasMyCircle" v-for="(item, index) in myCircleData" :key="index" :circlePath = "item" />
      <bm-local-search :keyword="mapKeyword" :selectFirstResult="selectFirstResult" :auto-viewport="true" :panel="false" @searchcomplete="searchcomplete" ></bm-local-search>
      <MyOverlay v-if="hasMyOverlay" v-for="(overlayInfo,index) in recordPointMy" :key="`overlay${index}`" :position="overlayInfo.point" :color="overlayInfo.color" :recordId="overlayInfo.recordId" :showEffectOn="overlayInfo.showEffectOn" @handleChangeRecordPoint="handleChangeRecordPoint"/>
      </slot>

    </baidu-map>
    <MyMapFactor v-if="hasMyMapFactor" style="position: absolute;top:10px;right:10px;" ref="checkMap" :checkListGroup="checkListGroup" @handleChangeCheckGroup="handleChangeCheckGroup"/>
    <MyInputSearch v-if="hasMyInputSearch" @handleChangeInputSearch="handleChangeInputSearch" style="position: absolute;top:10px;left:10px;" />
    <MyVideo v-if="myVideoShow" @handleCloseMyVideoShow="handleCloseMyVideoShow"/>
    <Count v-if="hasMyCount" style="position:absolute;top:20px;z-index:1;left: 50%;
    transform: translateX(-50%);"
             :countData="countData"/>
  </div>
</template>

<script>
// import { FlashMarker } from './flashMarker.js'
import BaiduMap from "vue-baidu-map/components/map/Map.vue";
import BmNavigation from "vue-baidu-map/components/controls/Navigation";
import BmOverviewMap from "vue-baidu-map/components/controls/OverviewMap";
import { BmlMarkerClusterer } from "vue-baidu-map"; // 聚合
import BmMarker from "vue-baidu-map/components/overlays/Marker";
import BmPointCollection from "vue-baidu-map/components/overlays/PointCollection";
import { BmLocalSearch } from "vue-baidu-map";
import MyOverlay from "@/components/ly_components/map/MyOverlay.vue"; // 自定义覆盖物

import BmOverlay from "vue-baidu-map/components/overlays/Overlay";

import MyMarker from "@/components/ly_components/map/MyMarker.vue"; // 自定义的marker

import MyPolyline from "@/components/ly_components/map/MyPolyline.vue";
import MyCircle from "@/components/ly_components/map/MyCircle";

import MyMapFactor from "@/components/ly_components/map/MyMapFactor";
import MyInputSearch from "@/components/ly_components/map/MyInputSearch";

import MyMarkerClusterer from "@/components/ly_components/map/MyMarkerClusterer";

import MyVideo from "@/components/ly_components/map/MyVideo"

import Count from "@/components/ql_component/Count";
import { cloneDeep } from "lodash";
import { deepClone } from '../../../utils';

export default {
  components: {
    BaiduMap,
    BmNavigation,
    BmOverviewMap,
    BmlMarkerClusterer,
    BmMarker,
    BmPointCollection,
    BmLocalSearch,
    MyOverlay,
    // BmOverlay,
    MyMarker,
    MyPolyline,
    MyCircle,
    MyMapFactor,
    MyInputSearch,
    MyMarkerClusterer,
    MyVideo,
    Count
  },
  props: {
    showSourceCheck: {
      type: Boolean,
      default: true
    },
    baiduMapId: {
      type: String,
      default: "MyMap"
    },
    baiduMapWidth: { // 地图视口宽度
      type: String,
      default: '450px'
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    abnormalInfo: {
      type: Object,
      default: function() {
        return {};
      }
    },
    hasBmNavigation: { // 地图放大缩小工具
      type: Boolean,
      default: false
    },
    hasBmOverviewMap: { // 缩略图
      type: Boolean,
      default: false
    },
    hasMyMarker: { // 单个标记点
      type: Boolean,
      default: false
    },
    hasBmPointCollection: { // 聚集点
      type: Boolean,
      default: false
    },
    hasMyMarkerClusterer: { // 点的聚合
      type: Boolean,
      default: false
    },
    hasMyPollyline: { // 折线
      type: Boolean,
      default: false
    },
    hasMyMapFactor: { // 因子
      type: Boolean,
      default: false
    },
    hasMyInputSearch: { // 搜索框
      type: Boolean,
      default: false
    },
    hasMyCircle: {
      type: Boolean,
      default: false
    },
    hasMyOverlay: {
      type: Boolean,
      default: false
    },
    hasMyCount: {
      type: Boolean,
      default: false
    },
    mapKeyword: { // 地图搜索关键字
      type: String,
      default: ""
    },
    selectFirstResult: {
      type: Boolean,
      default: true
    },
    center: {
      type: Object,
      default: function(){
        return {lng: 105.000, lat: 38.000}
      }
    },
    markerPoints: {
      type: Array,
      default: function() {
        return []
      }
    },
    markerPointsList: { // 标记坐标
      type: Array,
      default: function() {
        return [
          {point:{ lng: 116.46665, lat: 39.914112, },iconUrl: {url:require("../../../assets/info_images/source.png"),size:{width:46,height:46}}},
          {point:{ lng: 116.46865, lat: 39.914112, },iconUrl: {url:require("../../../assets/info_images/startPoint.png"),size:{width:46,height:46}}},
          {point:{ lng: 116.615829, lat: 39.872482, },iconUrl: {url:require("../../../assets/info_images/endPoint.png"),size:{width:46,height:46}}}
        ]
      }
    },
    recordPoint: { // 记录点信息，出库，运输，作业，入库
      type: Array,
      default: function(){
        return [
          {
              recordId: 1, // 记录id
              recordType: "checkout", // 表示出库
              point: { lng: 116.404, lat: 39.915 } // 坐标位置
          }
        ]
      }
    },
    markerPointInfos: {
      type: Array,
      default: function() {
        return [
          //   {
          //   point: { lng: 116.404, lat: 39.915 },
          //   infoWindowType: "enterprise",
          //   infoWindowShow: false,
          //   markerIcon: {url: require('../../../assets/info_images/enterprise.png'), size: {width: 32, height: 32}},
          //   infoWindowInfo: {
          //     enterpriseInfo: {
          //       enterpriseId: 1,
          //       enterpriseImgUrl: "图片",
          //       enterpriseName: "**某某企业",
          //       enterpriseAddress: "某某区",
          //       enterpriseTel: "000-000",
          //       enterpriseAd: "88路88号",
          //       enterpriseOrigin1: "附属库源",
          //       enterpriseOrigin2: "源库A",
          //       enterpriseOrigin3: "源库B"
          //     }
          //   }
          // },
          // {
          //   point: { lng: 116.304, lat: 39.915 },
          //   infoWindowType: "enterpriseOrigin",
          //   infoWindowShow: false,
          //   markerIcon: {url: require('../../../assets/info_images/ora_source.png'), size: {width: 32, height: 32}},
          //   infoWindowInfo: {
          //     enterpriseOriginInfo: {
          //       enterpriseOriginId: 2,
          //       enterpriseOriginName: "**企业**源库",
          //       enterpriseOriginAddress: "某某区",
          //       enterpriseOriginTel: "000-000",
          //       enterpriseOriginCity: "默默市",
          //       videoUrl: ""
          //     }
          //   }
          // }
        ]
      }
    },
    polylinePath: {
      type: Array,
      default: function() {
        return [
          { lng: 116.404, lat: 39.915 },
          { lng: 116.405, lat: 39.92 },
          { lng: 116.423493, lat: 39.907445 },
          { lng: 116.473493, lat: 39.927445 }
        ]
      }
    },
    countData: {
      type: Array,
      default: function() {
        return [
				{
					name: "源总数",
					count: 200
				},
				{
					name: "企业总数",
					count: 26
				},
				{
					name: "人员总数",
					count: 390
				}
      ]
      }
    },
    myCircleData: {
      type: Array,
      default: function() {
        return [
          {center: {
            lng: 12,
            lat: 12
          },
          radius: 60}
        ]
      }
    }
  },
  data() {
    return {
      // center: { lng: 0, lat: 0 }, // lng: 105.000, lat: 38.000
	renderMap: false,
      zoom: 4, // 3
      points: [],
      active: false,
      inputSearchKeyWords: "", // 搜索框字段
      checkListGroup: cloneDeep(MAP_DEFAULT_SELECT_PLY),// 选项框列表
      polylinePath1: [
        { lng: 116.46865, lat: 39.914112, },
        { lng: 116.46865, lat: 39.877355, },
        { lng: 116.556612, lat: 39.875583, },
        { lng: 116.615829, lat: 39.872482, }
      ],
      polylinePath2: [
        { lng: 116.46865, lat: 39.914112, },
        { lng: 116.46865, lat: 39.877355, },
        { lng: 116.556612, lat: 39.875583, },
        { lng: 116.615829, lat: 39.872482, }
      ],
	  recordPointMy: [],
      /*markerPoints: [
        {
          point: { lng: 116.404, lat: 39.915 },
          infoWindowType: "enterprise",
          infoWindowShow: false,
          markerIcon: {url: require('../../../assets/info_images/enterprise.png'), size: {width: 32, height: 32}},
          infoWindowInfo: {
            enterpriseInfo: {
              enterpriseId: 1,
              enterpriseImgUrl: "图片",
              enterpriseName: "**某某企业",
              enterpriseAddress: "某某区",
              enterpriseTel: "000-000",
              enterpriseAd: "88路88号",
              enterpriseOrigin1: "附属库源",
              enterpriseOrigin2: "源库A",
              enterpriseOrigin3: "源库B"
            }
          }
        },
        {
          point: { lng: 116.304, lat: 39.915 },
          infoWindowType: "enterpriseOrigin",
          infoWindowShow: false,
          markerIcon: {url: require('../../../assets/info_images/ora_source.png'), size: {width: 32, height: 32}},
          infoWindowInfo: {
            enterpriseOriginInfo: {
              enterpriseOriginId: 2,
              enterpriseOriginName: "**企业**源库",
              enterpriseOriginAddress: "某某区",
              enterpriseOriginTel: "000-000",
              enterpriseOriginCity: "默默市",
              videoUrl: ""
            }
          }
        },
        {
          point: { lng: 116.404, lat: 40.015 },
          infoWindowType: "car",
          infoWindowShow: false,
          markerIcon: {url: require('../../../assets/info_images/car.png'), size: {width: 32, height: 32}},
          infoWindowInfo: {
            carInfo: {
              carId: 6,
              carCode: "342252",
              carHasOrigin: "是",
              carOriginCode: "fdf",
              carNuclideCode: "核素",
              carOriginNum: "剂量",
              videoUrl: ""
            }
          }
        },
        {
          point: { lng: 116.404, lat: 40.115 },
          infoWindowType: "person",
          infoWindowShow: false,
          markerIcon: {url: require('../../../assets/info_images/person.png'), size: {width: 32, height: 32}},
          infoWindowInfo: {
            personInfo: {
                personId: 5,
                personName: "某某",
                personImgUrl: "图片",
                personType: "******",
                personTel: "7897979",
              }
          }
        },
        {
          point: { lng: 116.404, lat: 39.815 },
          infoWindowType: "origin",
          infoWindowShow: false,
          markerIcon: {url: require('../../../assets/info_images/source.png'), size: {width: 32, height: 32}},
          infoWindowInfo: {
            originInfo: {
                originId: 6,
                originName: "某某源",
                originUse: "",
                originType: "",
                originCode: "",
                originToolCode: "",
                videoUrl: ""
              },
          }
        }
      ],*/
      icons: [],
      citys: [
        {
          name: "北京",
          lnglat: ["116.3", "39.9"],
          color: "#5070FF",
          type: "circle",
          speed: 0.5
        },
        {
          name: "上海",
          lnglat: ["121.29", "31.11"],
          color: "#6EE7FF",
          type: "ellipse",
          speed: 1,
          max: 40
        },
        {
          name: "福建",
          lnglat: ["117.984943", "26.050118"],
          color: "#90EE90",
          type: "circle",
          speed: 0.45
        },
        {
          name: "广东",
          lnglat: ["113.394818", "23.408004"],
          color: "#f8983a",
          type: "circle",
          speed: 0.9
        },
        {
          name: "广西",
          lnglat: ["108.924274", "23.552255"],
          color: "#FAFA32",
          type: "ellipse",
          speed: 0.8,
          max: 50
        }
      ],
      myVideoShow: false,
      _map: null,
      _BMap: null,
      markerPointsNew: [],
	  prive_center:  {lng: 105.000, lat: 38.000},
	  centerOwn: {lng: 105.000, lat: 38.000}
    };
  },
  created() {
    this.addPoints();
    this.handleChangeMapData()
    this.polylinePath1 = [...this.polylinePath]
    this.polylinePath2 = [...this.polylinePath]
    this.recordPointMy = [...this.recordPoint]
  },
  mounted() {},
  beforeDestroy() {},
  watch: {
	center(value){
		this.centerOwn = value;
		this.prive_center = value
	},
	recordPoint(value){
		// debugger
    this.recordPointMy = cloneDeep(value)
    console.log('this.recordPointMy',this.recordPointMy)
	},
    polylinePath(value) {
      this.polylinePath1 = [...value]
      this.polylinePath2 = [...value]
    },
    markerPoints(value){

      console.log(this._map)
      console.log(this._BMap)
      // debugger
      // this._map && this._map.clearOverlays()
      this.markerPointsNew = value
    },
    showSourceCheck(value){
      if(value){
        // console.log(value,'sourceCheck')
        this.$refs.checkMap.openSource()
        this.checkListGroup = Object.assign(this.checkListGroup, { // 选项框列表
          checkList1: [
            "enterpriseOrigin",
            "origin"
          ],
          checkList2: [
            1,
            2,
            3,
            4,
          ],
          checkList3: [
            "036ca399-4447-4333-bc6d-9247a2aeee0d",
            "6b8bd743-44b9-4e9c-b919-32541d50d890",
            "5f995588-f35b-4db0-a3c8-4397ab594619",
            "9c2c9035-b408-447b-b4a9-eb1a47e90433",
            "419bd883-f484-4a49-99dc-2c6cacd43f53",
          ],
          checkList4: this.checkListGroup.checkList4
        })
        let params = cloneDeep(this.checkListGroup)
        this.$emit("handleChangeCheckGroup",params)
      }else{
        this.$refs.checkMap.closeSource()
      }
    },
    markerPointsNew(value){
      if(value) {
          if(this.hasMyMarkerClusterer && this.markerPointsNew.length) {
            const centerPoint = this.markerPointsNew[0].point
            // console.log(111111)
            // console.log(this.center)
            this.$emit("changeCenterPoint",centerPoint)
          }
      }
    },
  },
  methods: {
    handler({ BMap, map }) {
      console.log(BMap, map);
      // this.center.lng = 116.517147;
      // this.center.lat = 39.875253;
		this.zoom = 13;
		this._BMap = BMap;
		this._map = map;

		// this.centerOwn = this.prive_center
		var sy = new BMap.Symbol(BMap_Symbol_SHAPE_BACKWARD_OPEN_ARROW, {
			scale: 0.4,//图标缩放大小
			strokeColor:'#fff',//设置矢量图标的线填充颜色
			strokeWeight: '1',//设置线宽
		});
		let icons = new BMap.IconSequence(sy, '10', '30');
      	this.icons.push(icons)
      // let sy = new BMap.Symbol(BMap_Symbol_SHAPE_STAR, { // BMap_Symbol_SHAPE_BACKWARD_OPEN_ARROW
      //     scale: 0.6,//图标缩放大小
      //     strokeColor:'#000',//设置矢量图标的线填充颜色
      //     strokeWeight: '2',//设置线宽
      // });
      // let icon = new BMap.IconSequence(sy, '10', '30',true);
      // console.log(icon,'icon')
		this.renderMap = true;

      // let flashMarkerLayer = new FlashMarker(map, this.citys,BMap)
    },
    clickHandler(e) {
      alert(`单击点的坐标为：${e.point.lng}, ${e.point.lat}`);
    },
    addPoints() {
      const points = [];
      for (var i = 0; i < 1000; i++) {
        const position = {
          lng: Math.random() * 40 + 85,
          lat: Math.random() * 30 + 21
        };
        points.push(position);
      }
      this.points = points;
    },
    // draw ({el, BMap, map}) {
    //   const pixel = map.pointToOverlayPixel(new BMap.Point(116.404, 39.915))
    //   el.style.left = pixel.x - 60 + 'px'
    //   el.style.top = pixel.y - 20 + 'px'
    // },
    // handleClick () {
    //   global.alert('Well done.')
    // },
    handleChangeCheckGroup(value,index){ // 选项框变化后的回调
      // this.checkListGroup[index] = value;
      let params = cloneDeep(this.checkListGroup)
      this.$emit("handleChangeCheckGroup",params)
    },
    handleChangeInputSearch(value) { // 搜索框变化后的回调
      this.inputSearchKeyWords = value
      this.handleChangeMapData()
    },
    handleChangeMapData() { // 改变数据源,参数变化
      let params = {}
      params.inputSearchKeyWords = this.inputSearchKeyWords
      for(let key in this.checkListGroup) {
        params[key] = this.checkListGroup[key].join(",")
      }
      params.checkListGroup = deepClone(this.checkListGroup)
      this.$emit("handleChangeMapData",params)
    },
    handleChangePolylinePath1(polylinePath) {
    	this.polylinePath1 = polylinePath
    },
    handleChangePolylinePath2(polylinePath) {
    	this.polylinePath2 = polylinePath
    },
    searchcomplete(results){ // 搜索完成后的回调
      this.$emit("searchcomplete",results)
    },
    handleChangeMyVideoShow() {
      this.myVideoShow = true
    },
    handleCloseMyVideoShow() {
      this.myVideoShow = false
    },
    handleChangeRecordPoint(value) { // 点击记录点，出库，运输
      this.$emit("handleChangeRecodeId",value)
    }
  }
};
</script>
<style lang="scss" scoped>
.bm-view {
  width: 100%;
  // height: 450px;
}

</style>
<style lang="scss">
  #MyMap{
    .BMap_cpyCtrl {
      display: none;
    }
    .anchorBL{
      display:none;
    }
    #all_count{
      .count .title {
        color: #000 !important;
      }
    }
    .BMap_Marker{
      background-size: cover !important;
    }
  }

  #originMapId{
    .BMap_cpyCtrl {
      display: none;
    }
    .anchorBL{
      display:none;
    }
  }

  #MyMap {
      #all_count{
        width: 560px!important;
      }
  }

  @media screen and (max-width: 1750px) {
    #MyMap {
      #all_count{
        transform: translateX(-50%) scale(0.8)!important;
    }
  }
}

@media screen and (max-width: 1450px) {
    #MyMap {
      #all_count{
        transform: translateX(-50%) scale(0.6)!important;
        margin: 0;
    }
  }
}

</style>
